package com.example.myapplication.lunbo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.example.day01.R;

import java.util.ArrayList;
import java.util.List;

public class BannerActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {
   ViewPager bannerVp;
   LinearLayout pointLayout;
   int []imgIds={R.mipmap.image1,R.mipmap.image2,R.mipmap.image3,R.mipmap.image4,R.mipmap.image5};
   List<ImageView>viewList;//存放ViewPager轮播的图片
    List<ImageView> pointList;
    BannerAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_banner);
        bannerVp=findViewById(R.id.banner_vp);
        pointLayout=findViewById(R.id.banner_layout);
        //找到数据源
     viewList=new ArrayList<>();//初始化
        pointList=new ArrayList<>();
        for (int i = 0; i <imgIds.length ; i++) { //创建ImageView添加到集合里
            ImageView iv=new ImageView(this);
            iv.setImageResource(imgIds[i]);
            iv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));//设置View的宽高，在代码写空间要手动设置
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            viewList.add(iv);
            //动态生成指示器
            ImageView pIv=new ImageView(this);
            pIv.setImageResource(R.mipmap.a3);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.rightMargin=20;

            pIv.setLayoutParams(lp);
            pointList.add(pIv);//为了便于管理添加到集合
            pointLayout.addView(pIv);//为了显示添加到布局;


        }
        pointList.get(0).setImageResource(R.mipmap.a2);//第一个为绿色
        //设置适配器
         adapter= new BannerAdapter(viewList);
         bannerVp.setAdapter(adapter);
         //设置ViewPager监听器,滑动的位置
        bannerVp.addOnPageChangeListener(this);

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i <pointList.size(); i++) {
            pointList.get(i).setImageResource(R.mipmap.a3);
        }
        pointList.get(position%viewList.size()).setImageResource(R.mipmap.a2);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
